'use strict';
const Controller = require('egg').Controller;
const fs = require('fs');
const path = require('path');
const sendToWormhole = require('stream-wormhole');
const awaitWriteStream = require('await-stream-ready').write;
const mkdirp = require('mkdirp');
/**
 * @controller BookController 书籍相关接口
 */
class BookController extends Controller {

  async index() {
    /**
     * @description 查询书籍
     * @router get /api/book
     * @request queryt string name
     */
    const ctx = this.ctx;
    const name = ctx.params.name;
    let result = null;
    if (name) {
      // 查询具体名字的书籍
      result = await ctx.service.book.getBookByName({
        name,
      });
    } else {
      // 如果名字不存在，则查询全部书籍
      result = await ctx.service.book.getAllBook();
    }
    ctx.status = 200;
    ctx.body = result;
  }
  async getHomeData() {
    /**
     * @description 获取首页书籍数据,默认返回已完结已上架的书籍
     * @router get /api/getHomeData
     */
    const ctx = this.ctx;
    let result = null;
    result = await ctx.service.book.getHomeData();
    ctx.status = 200;
    ctx.body = result;
  }

  // 获取所有书籍
  async getAllbook() {
    const ctx = this.ctx;
    const result = await ctx.service.book.getAllBook(ctx.query);
    ctx.status = 200;
    ctx.body = result;
  }
  // 添加一本书
  async create() {
    /**
     * @description 添加书籍
     * @router post /api/book
     * @request body addBook data  请求数据
     */
    const { ctx } = this;
    const rule = {
      name: { type: 'string', required: true, message: '书籍名称不能为空' },
      author: { type: 'string', required: true, message: '作者不能为空' },
      brief: { type: 'string', required: true, message: '简介不能为空' },
      classifyId: 'int',
    };
    const data = ctx.request.body;
    // console.log('create data:',data)
    // 校验不通过会抛出异常，异常会在middler统一处理
    await ctx.validate(rule, data);

    // let data = {
    //   name:'射雕英雄传',
    //   author:'金庸',
    //   brief:'郭靖与黄蓉的故事'
    // }
    const result = await ctx.service.book.addBook(data);
    ctx.status = 200;
    ctx.body = result;
  }
  // 删除一本书，只逻辑删除，不会物理删除
  async destroy() {
    /**
     * @description 删除书籍
     * @router delete /api/book
     * @request query string id 书籍id
     */
    const { ctx } = this;
    const id = ctx.params.id;
    if (id) {
      const result = await ctx.service.book.deleteBookById({ id });
      ctx.status = 200;
      ctx.body = result;
    } else {
      ctx.status = 400;
      ctx.body = '参数错误';
    }
  }
  async update() {
    /**
     * @description 更新书籍
     * @router PUT /api/book
     * @request query string id 书籍id
     */
    const { ctx } = this;
    const id = ctx.query.id;
    const data = ctx.request.body;
    if (id && data) {
      const result = await ctx.service.book.updateBookById(id, data);
      ctx.status = 200;
      ctx.body = result;
    } else {
      ctx.status = 400;
      ctx.body = '参数错误 data:' + data;
    }
  }
  async getBookByClassify() {
    /**
     * @description 根据分类id获取推荐图书
     * @router GET /api/getBookByClassify
     * @request query string classifyId 分类id
     * @request query string pageSize 每一页显示的记录数
     * @request query string curPage 当前页码
     */
    const { ctx } = this;
    const classifyId = ctx.query.classifyId;
    const pageSize = ctx.query.pageSize;
    const curPage = ctx.query.curPage;
    const restQuery = {
      status: ctx.query.status,
      isShow: ctx.query.isShow,
    };
    if (classifyId) {
      const result = await ctx.service.book.getBookByClassify(classifyId, pageSize, curPage, restQuery);
      ctx.status = 200;
      ctx.body = result;
    } else {
      ctx.status = 400;
      ctx.body = '分类id不存在';
    }
  }
  async getBookById() {
    /**
     * @description 根据id获取书籍信息
     * @router GET /api/getBookById
     * @request query string id 书籍id
     */
    const { ctx } = this;
    const id = ctx.query.id;
    const result = await ctx.service.book.getBookById(id);
    ctx.status = 200;
    ctx.body = result;
  }

  async getBooksByName() {
    /**
     * @description 根据书籍名字获取书籍信息
     * @router GET /api/getBooksByName
     * @request query string name 书籍名字
     */
    const { ctx } = this;
    const result = await ctx.service.book.getBooksByName(ctx.query);
    ctx.status = 200;
    ctx.body = result;
  }

  async addBookCvById() {
    /**
     * @description 统计书籍被点击的次数
     * @router GET /api/addBookCvById
     * @request query string id 书籍id
     */
    const { ctx } = this;
    const id = ctx.query.id;
    const result = await ctx.service.book.addBookCvById(id);
    ctx.status = 200;
    ctx.body = result;
  }
  async uploadBook() {
    /**
     * @description 上传书籍
     * @router PUT /api/uploadBook
     */
    const { ctx } = this;
    let result;
    const stream = await ctx.getFileStream();
    try {
      const id = stream.fields.bookId;
      const delimiter = stream.fields.delimiter;
      const chaptersNum = stream.fields.chaptersNum;
      const canSplit = stream.fields.canSplit;
      const classifyId = stream.fields.classifyId;
      // return;
      const uploadPath = path.join(this.config.uploadEbookDir, classifyId);
      await mkdirp(uploadPath);
      // 给书名添加一个
      const ebookPath = path.join(uploadPath, stream.filename);
      const writeStream = fs.createWriteStream(ebookPath);
      // 可以分章节的，需要在service中分章节，不需要分章节的，直接上传上去就可以。
      await awaitWriteStream(stream.pipe(writeStream));
      // 经过formdata传过来之后，boolean就变成了string
      if (canSplit === 'true') {
        result = await ctx.service.book.splitBook2Category(id, ebookPath, delimiter, chaptersNum);
      } else {
        // 不分章节
        const uPathResult = await ctx.service.book.updateBookPathAndStatus(id, ebookPath, 1);
        if (uPathResult.code === 0) {
          result = {
            code: 0,
            msg: '书籍上传成功',
          };
        } else {
          result = {
            code: -1,
            msg: '书籍上传失败',
          };
        }

      }
    } catch (error) {
      await sendToWormhole(stream);
      ctx.status = 200;
      ctx.body = {
        code: -1,
        msg: '上传书籍出错,' + JSON.stringify(error),
      };
    }
    ctx.status = 200;
    ctx.body = result;


    // const data = ctx.request.body
    //  if(data){
    //    const result = await ctx.service.book.uploadBook(data)
    //    ctx.status = 200
    //    ctx.body = result
    //  }else{
    //    ctx.status = 400
    //    ctx.body = '参数错误 data:' + data
    //  }
  }


  async downloadBook() {
    /**
     * @description 上传书籍
     * @router get /api/downloadBook
     * @request query bookId string
     */
    // const originPath = this.config.uploadEbookDir.slice(3); // 去掉app路径
    const { ctx } = this;
    const bookPath = decodeURIComponent(ctx.query.bookPath);
    const bookName = decodeURIComponent(ctx.query.bookName);
    const originBookName = bookPath.slice(bookPath.indexOf(bookName));
    // const originBookName = book.path.replace(originPath, '');


    const isExist = fs.existsSync('app' + bookPath);
    if (isExist) {
      ctx.attachment(originBookName);
      ctx.set({ 'Content-Type': 'application/octet-stream' });
      const stream = fs.createReadStream('app' + bookPath);
      ctx.body = stream;
    } else {
      ctx.body = '<div style="padding:8vw 4vw;font-size:4vw">文件因为某些原因被删除，您可以回到<a style="color:red" href="//localhost:7001">首页</a>。或者联系管理员询问书籍情况<a style="color:red" href="mailto:boyashuyuan@yandex.com">boyashuyuan@yandex.com</a></div>';
    }


  }
}

module.exports = BookController;
